<?php

namespace Wap\Controller;

use Think\Controller;
use Think\Model;
use Wap\Model\PraiseItemRecordModel;
use Wap\Service\PraiseService;
use Wap\Service\RuleService;
use Wap\Service\WeixinService;
use Wap\Service\CustomerService;

class PraiseController extends WapController
{

    public $_praise;//活动信息
    public $wxuser;//活动绑定的微信号
    public $user;//微信用户
    public $ori_praise_token;//--投票活动原始token--
    public $secure_actions = array("fetch_one", "upload", "edit");
    public $unsecure_actions = array("index", "introduction", "teacher", "teacherdetail");

    public function __construct()
    {
        parent::__construct();

        $this->handleCriteriaPraise();
        $this->handleCriteriaWxuser();

        $wxJSApi = WeixinService::buildWXJSApi($this->wxuser);
        if (empty($wxJSApi)) {
            header("Content-type: text/html; charset=utf-8");
            die('服务器繁忙请稍后！');
        }
        $this->assign('nonceStr', $wxJSApi['noncestr']);
        $this->assign('wxTicket', $wxJSApi['ticket']);
        $this->assign('timestamp', $wxJSApi['timestamp']);
        $this->assign('wxSha1', $wxJSApi['sha1']);

        $this->assign("wxuser", $this->wxuser);
        $this->assign("praise", $this->_praise['id']);//TODO: should be clear
        $this->assign("praiseContent", $this->_praise);//TODO: should be clear
        $this->assign("info", $this->_praise['link']);
        $imgurl = "";
        if (!empty($this->_praise) && !empty($this->_praise['picurl'])) {
            $picArr = explode(";", $this->_praise['picurl']);
            $imgurl = $picArr[0];
        }
        $this->assign("imgurl", $imgurl);//TODO: should be clear

        $share_info = json_decode($this->_praise['info'], true);
        $share_title = $this->_praise['title'];
        $share_desc = $this->_praise['title'] . "，快来为TA添人气吧！";
        $share_pic = $imgurl;
        if (!empty($share_info['share_title'])) {
            $share_title = $share_info['share_title'];
        }
        if (!empty($share_info['share_desc'])) {
            $share_desc = $share_info['share_desc'];
        }
        if (!empty($share_info['share_pic'])) {
            $share_pic = 'http://' . $_SERVER['HTTP_HOST'] . $share_info['share_pic'];
        }
        $this->assign('share_title', $share_title);
        $this->assign('share_desc', $share_desc);
        $this->assign('share_pic', $share_pic);
    }

    /**
     *函数名: index
     *函数描述: 获取微信网页静默授权CODE、加载所有作品主页模板
     * @param string $_GET ['code'];
     * @return object 模板
     */
    public function index()
    {
//        return $this->display('index_new');
        if (I('get.type', '', '') != 'info') {
            if ($this->_praise['style'] == 1) {
                return $this->display();
            } else {
                return $this->display("zan");
            }
        } else {
            return $this->display('info');
        }
    }

    /**
     *函数名: introduction
     *函数描述: 渲染活动介绍模板
     * @return object 模板
     */
    public function introduction()
    {
        $this->display();  //"active"
    }

    /**
     *函数名: upload   原名称attend_index
     *函数描述: 渲染上传作品页面模板
     * @return object 模板
     */
    public function upload()
    {
        $this->handleCriteriaURL();
        $this->handleCriteriaUser();
        $this->handleCriteriaCustomer();

        $customer_id = -1;
        $online = CustomerService::check();
        if ($online) {
            $customer_id = CustomerService::getID();
        }
        $this->assign("customer", $customer_id);

        $this->display();  //原页面attend.html
    }

    public function uploadTest()
    {

        $customer_id = -1;
        $online = CustomerService::check();
        if ($online) {
            $customer_id = CustomerService::getID();
        }
        $this->assign("customer", $customer_id);

        $this->display("upload");  //原页面attend.html
    }


    public function teacher()
    {
        $this->display();
    }

    public function teacherdetail()
    {
        $praise_id = I('get.praise', -1, '');
        $teacher_name = I('get.teacher_name', '', '');
        $teacher_telephone = I('get.teacher_telephone', '', '');

        $result = D('teacher')->get_rank($praise_id, $teacher_name, $teacher_telephone);
        $this->assign("teacher", $result);
        $this->display();
    }

    public function home()
    {
        $user = I("get.user", -1, "");
        $praise = I("get.praise", -1, "");
        $customer_id = CustomerService::getID();
        $online = CustomerService::check();

        if (!$online) {
            $try = session("try.home");
            if ($try === null) {
                session("try.home", 1);
                header("Location: " . U('Wap/Praise/home', array('praise' => I('praise', -1, ''))));
                exit();
            } else if ($try < 3 && $try > 0) {
                $try = ($try + 1) % 3;
                session("try.home", $try);
                header("Location: " . U('Wap/Praise/home', array('praise' => I('praise', -1, ''))));
                exit();
            } else if ($try === 0) {
                session("try.home", null);
                $this->error("信息异常, 请尝试重新登录", "#");
            }
        }
        session("try.home", null);

        $condition['uid'] = $customer_id;
        $condition['praise_id'] = $praise;
        $datas = D("praise_item")->where($condition)->select();

        $status = PraiseService::access($praise);
        $this->assign("status", $status);
        $this->assign("datas", $datas);
        $this->display();
    }

    /**
     *函数名: fetch_one
     *函数描述: 查看具体某一幅作品信息
     * @param int $_GET ['id'] 作品ID
     * @return object 渲染作品详情页模板、模板赋值
     */
    public function fetch_one()
    { //查看一幅具体作品
        $this->handleCriteriaURL();
        $this->handleCriteriaUser();

        $id = I("get.id", -1, "");//TODO: 输入控制
        $this->assign("id", $id);
        $praise = I('get.praise', -1, '');

        $condition['esm_praise_item.id'] = $id;

        $datas = D('praiseItem')->fetch_by_id($id);
        $rank = D("praiseItem")->fetch_rank_by_id($datas['id']);
        $check = RuleService::is_good($praise, $this->user['openid'], array('updated_time' => time(), 'praise' => $praise, 'openid' => $this->user['openid'], 'pid' => $id));
        $checked = $check['error'] ? 0 : 1;

        if (!count($datas)) {
            $this->error('该作品不存在、或未被审核通过', '#');
        }
        M("praise_item")->where(['id' => $id])->setInc("pv");
        //--获取投票项属性--
        $type = M("praise")->where(['id' => $praise])->getField("type");
        $this->assign('type', $type);
        $this->assign('openid', $this->user['openid']);
        $this->assign('unionid', session("union_id"));
        $this->assign("followLink", "http://" . $_SERVER['HTTP_HOST'] . "/Wap/Praise/index/praise/" . $this->_praise['id']);
        $this->assign("rank", $rank);
        $this->assign("result", $datas);
        $this->assign('checked', $checked);

        $cond_live['chat_id'] = $id;
        $cond_live['status'] = 1;
        $cond['topic_id'] = -$praise;
        $comments = M("live_comment")->where($cond_live)->order("id asc")->select();
        $this->assign('comments', $comments);
        if ($this->_praise['style'] == 1) {
            return $this->display();
        } else {
            return $this->display("zan_fetch_one");
        }
    }

    public function edit()
    {
        $this->handleCriteriaURL();
        $this->handleCriteriaUser();
        $this->handleCriteriaCustomer();

        $customer_id = CustomerService::getID();
        if (!$customer_id) {
            $this->error("当前用户不在线", "#");//TODO:
        }

        $condition['praise_id'] = I("get.praise", -1, '');
        $condition['id'] = I('get.id', -1, '');
        $condition['status'] = -1;

        // $this->share['link'] = C("SITE_URL").'/'.U('Wap/Praise/index', array( 'praise' => $condition['praise'] ) );

        $data = D('praise_item')->where($condition)->find();

        // $this->assign( "share", $this->share );
        $this->assign("customer", $customer_id);
        $this->assign("data", $data);
        $this->display("upload");
    }

    public function code()
    {
        $praise_id = I("get.praise", "-1", "");
        $id = I("get.id", "", "");
        Vendor("phpqrcode.phpqrcode");
        $QRcode = new \QRcode();
        $url = C("SITE_URL") . "/Wap/Praise/index?praise=" . $praise_id;
        if (!empty($id)) {
            $url = C("SITE_URL") . "/Wap/Praise/fetch_one?praise=" . $praise_id . "&id=" . $id;
        }
        // 纠错级别：L、M、Q、H
        $level = 'L';
        // 点的大小：1到10,用于手机端4就可以了
        $size = 4;
        $QRcode::png($url, false, $level, $size);
    }

    /*
    *是否合法活动
    */
    private function handleCriteriaPraise()
    {
        $this->praise = I("get.praise", -1, "");
//        trace($this->praise,"test:","SQL");
        $result = PraiseService::is_good($this->praise, time());
        $this->_praise = PraiseService::getPraise($this->praise);
        if ($result['good'] === false) {
            $this->error($result['msg'], "#");
        }
    }

    /*
    *静默授权url生成
    */
    private function handleCriteriaURL()
    {
        $code = I("get.code", "", "");
        if (!$code) {
            $url = C('SITE_URL') . $_SERVER['REQUEST_URI'];

            //---借权并需要强制关注用户使用网页授权，其它情况使用静默授权---
            if (!empty($this->ori_praise_token) && ($this->_praise['showpic'] == 1)) {
                $url = WeixinService::snsapiUserInfoLink($url, $this->wxuser['appid']);
            } else {
                $url = WeixinService::buildOauthURI($url, $this->wxuser['appid']);
            }
            header("Location: " . $url);
            exit();
        } else {
//            trace( $_SERVER, "server", "SQL" );
        }
    }

    /*
    *微信公众号信息
    */
    private function handleCriteriaWxuser()
    {
        //--借权并需要强制关注用户使用新媒体公众号--
        if (in_array($this->_praise['token'], PraiseItemRecordModel::$token_arr)) {
            $this->ori_praise_token = $this->_praise['token'];
            $this->_praise['token'] = 'iequde1415960341';
        }
        $this->wxuser = WeixinService::getWxuser($this->_praise['token']);
    }

    /*
    *微信用户
    */
    private function handleCriteriaUser()
    {
        $this->user = WeixinService::getUser();
        $code = I("get.code", "", "");
        if ($code) {
            WeixinService::setUser($this->wxuser['appid'], $this->wxuser['appsecret'], $code);
            $this->user = WeixinService::getUser();
            if(empty($this->user)){
                $url = C('SITE_URL') . $_SERVER['REQUEST_URI'];

                //---借权并需要强制关注用户使用网页授权，其它情况使用静默授权---
                if (!empty($this->ori_praise_token) && ($this->_praise['showpic'] == 1)) {
                    $url = WeixinService::snsapiUserInfoLink($url, $this->wxuser['appid']);
                } else {
                    $url = WeixinService::buildOauthURI($url, $this->wxuser['appid']);
                }
                header("Location: " . $url);
                exit();
            }
        }
        //--借权并需要强制关注用户需获取unionid--
        if (!empty($this->ori_praise_token) && ($this->_praise['showpic'] == 1)) {
            $url = sprintf("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN", $this->user['access_token'], $this->user['openid']);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 500);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
            $out = curl_exec($ch);
            curl_close($ch);
            $out = json_decode($out, 1);
            session("union_id", $out['unionid']);
        }
    }

    /*
    *注册用户
    */
    private function handleCriteriaCustomer()
    {
        CustomerService::setOpenID($this->user['openid']);
    }
}
